import { Injectable } from '@angular/core';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { of } from 'rxjs/observable/of';
import { catchError, map, switchMap } from 'rxjs/operators';

import { BasemapActionTypes, LoadBasemapsFail, LoadBasemapsSuccess } from '../actions';
import { BasemapsService } from '../../services';
import { Basemap } from '../../models';
import { funs } from '../../components/basemaps/basemaps.function';

@Injectable()
export class BasemapsEffects {

    constructor(
        private action$: Actions,
        private basemaps: BasemapsService
    ) {}

    serialize(basemaps: Basemap[] = []): Basemap[] {
        return basemaps.map((basemap: Basemap) => {
            return { ...basemap, init: funs[basemap.type] };
        });
    }

    @Effect()
    loadBasemaps$ = this.action$
        .pipe(
            ofType(BasemapActionTypes.LOAD_BASEMAPS),
            switchMap(() => {
                return this.basemaps.basemaps().pipe(
                    map((basemaps: Basemap[]) => new LoadBasemapsSuccess(this.serialize(basemaps))),
                    catchError(error => of(new LoadBasemapsFail(error)))
                );
            })
        );
}